import { MigrationInterface, QueryRunner } from 'typeorm';

export class FixUniqueConstraints1625000000002 implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<void> {
    try {
      // 检查表是否存在
      const tableExists = await queryRunner.hasTable('users');
      if (!tableExists) {
        console.log('users 表不存在，跳过此迁移');
        return;
      }

      // 检查并修复 email 字段的唯一约束
      try {
        // 删除现有的唯一索引
        await queryRunner.query(`DROP INDEX IF EXISTS IDX_fe0bb3f6520ee0469504521e71 ON users`);
        console.log('Dropped existing email unique index');
      } catch (error) {
        console.log('Email index does not exist or could not be dropped');
      }
      
      // 更新空值为 NULL
      await queryRunner.query(`
        UPDATE users SET email = NULL WHERE email = '';
      `);
      console.log('Updated empty email values to NULL');
      
      // 重新创建唯一索引 - 使用标准语法
      await queryRunner.query(`
        CREATE UNIQUE INDEX IDX_fe0bb3f6520ee0469504521e71 ON users (email);
      `);
      console.log('Created new email unique index');
      
      // 检查并修复 username 字段的唯一约束
      try {
        // 删除现有的唯一索引
        await queryRunner.query(`DROP INDEX IF EXISTS IDX_a000cca60bcf04454e72769949 ON users`);
        console.log('Dropped existing username unique index');
      } catch (error) {
        console.log('Username index does not exist or could not be dropped');
      }
      
      // 更新空值为唯一值
      await queryRunner.query(`
        UPDATE users SET username = CONCAT('user_', id) WHERE username = '';
      `);
      console.log('Updated empty username values');
      
      // 重新创建唯一索引
      await queryRunner.query(`
        CREATE UNIQUE INDEX IDX_a000cca60bcf04454e72769949 ON users (username);
      `);
      console.log('Created new username unique index');
      
      // 检查并修复 phone 字段的唯一约束
      try {
        // 删除现有的唯一索引
        await queryRunner.query(`DROP INDEX IF EXISTS IDX_phone ON users`);
        console.log('Dropped existing phone unique index');
      } catch (error) {
        console.log('Phone index does not exist or could not be dropped');
      }
      
      // 更新空值为唯一值
      await queryRunner.query(`
        UPDATE users SET phone = CONCAT('phone_', id) WHERE phone = '';
      `);
      console.log('Updated empty phone values');
      
      // 重新创建唯一索引
      await queryRunner.query(`
        CREATE UNIQUE INDEX IDX_phone ON users (phone);
      `);
      console.log('Created new phone unique index');
    } catch (error) {
      console.error('Error in migration:', error);
      throw error;
    }
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    // 简化回滚操作，避免删除所有列
    console.log('此迁移不支持回滚');
  }
}



